<template>
    <el-dialog :model-value="show" :title="id === 0 ? '添加用户' : '编辑用户'" @close="emit('Show', false)">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="账号" prop="username">
                <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="姓名" prop="nickName">
                <el-input v-model="form.nickName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input :disabled="id !== 0" v-model="form.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" prop="note">
                <el-input v-model="form.note" :rows="4" type="textarea" autocomplete="off" />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
                <el-radio-group v-model="form.status" class="ml-4">
                    <el-radio label="1" size="large">是</el-radio>
                    <el-radio label="2" size="large">否</el-radio>
                </el-radio-group>
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="NosubmitForm">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { addUserApi, getUserById, updateUserApi } from './api';

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    }
})

// 监听id的变化，获取用户信息
watch(() => props.id, () => {
    if (props.id !== 0) {
        getUserById(props.id).then((res) => {

            if (res.code === 200) {
                Object.assign(form, res.data)
            }
        })
    }
})

// 编辑框内ref数据
const formRef = ref<FormInstance>()
const emit = defineEmits(['Show'])

// 请求的参数
const form = reactive<List>({
    nickName: '',
    username: '',
    note: '',
    status: 0,
    password: '',
    email: ''
})

// 具体规则
const validateEmail = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入邮箱'))
    } else if (!/^\w+[@]\w+[.]\w+/.test(value)) {
        callback(new Error('请输入正确的邮箱'))
    } else {
        callback()
    }
}


// 规则
const rules = reactive({
    username: [{ required: true, trigger: "blur", message: "请填写用户名" }],
    nickName: [{ required: true, trigger: "blur", message: "请填写姓名" }],
    email: [{ validator: validateEmail, trigger: 'blur' }],
    password: [{ required: true, trigger: "blur", message: "请填写密码" }],
    status: [{ required: true, trigger: "blur", message: "请选择是否启用" }]
})

// 添加用户
const addUser = () => {
    ElMessageBox.confirm('确定要添加用户吗', '添加用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        addUserApi(form).then((res) => {
            if (res.code === 200) {
                // 提示
                ElMessage.success('添加成功')
                // 把dialog关闭
                // 刷新数据
                emit("Show", true);
                // 清空表单
                formRef.value?.resetFields();
            }
        })
    }).catch(() => {
        ElMessage.error('添加失败,请重新添加')
    })
}

// 修改用户
const editUser = () => {
    ElMessageBox.confirm('确定要修改用户信息吗', '修改用户信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
    }).then(() => {
        updateUserApi(form).then((res) => {
            if (res.code === 200) {
                // 提示
                ElMessage.success('修改成功')
                // 把dialog关闭
                // 刷新数据
                emit("Show", true);
                // 清空表单
                formRef.value?.resetFields();
            }
        })
    }).catch(() => {
        ElMessage.error('修改失败,请重新修改')
    })
}

// 点击确定
const submitForm = () => {
    formRef.value?.validate((bool: boolean) => {
        if (bool) {
            if (props.id === 0) {
                // 添加
                addUser()
            } else {
                // 修改
                editUser()
            }

        } else {
            ElMessage.error('请输入完整信息')
        }
    })
}

// 点击取消
const NosubmitForm = () => {
    // 把dialog关闭
    // 刷新数据
    emit("Show", false);
    // 清空表单
    formRef.value?.resetFields();
}


</script>
<style lang="less" scoped>

</style>